import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:permission_handler/permission_handler.dart';

class PermissionUtil {
  PermissionUtil(this._context);

  List<String> _list = [
    "您拒绝权限,请确定权限",
  ];

  BuildContext _context;

  void checkPermission({PermissionStatus status}) async {
    //申请权限     permission_handler: ^5.0.1+1

    Map<Permission, PermissionStatus> statuses = await [
      //存储
      Permission.storage,
      Permission.camera,
    ].request();

    statuses.forEach((key, value) {
      if (value.isGranted) {
        //权限通过
      } else if (value.isDenied) {
        //权限拒绝
        showPermissionDialog(_list[0], "重试", key);
      }
    });
  }

  ///是否去设置中心
  bool isGoAppSetting = false;

  ///msg 提示文案
  ///rightMsg  右侧按钮显示文案
  ///要申请的权限
  /// isUndetermined 可选参数,传入的是当前是否去设置中心
  void showPermissionDialog(String msg, String rightMsg, Permission permission,
      {bool isUndetermined = false}) {
    //使用苹果的dialog
    showCupertinoDialog(
        builder: (BuildContext context) {
          return CupertinoAlertDialog(
            title: Text("温馨提示"),
            content: Container(
              child: Text(msg),
            ),
            actions: [
              //左边按钮
              CupertinoDialogAction(
                child: Text("关闭应用"),
                onPressed: () {
                  //关闭引用
                  closeAPP();
                },
              ),
              //右边
              CupertinoDialogAction(
                child: Text(rightMsg),
                onPressed: () {
                  //关闭弹框
                  Navigator.pop(context);
                  if (isUndetermined) {
                    isGoAppSetting = true;
                    //去设置中心
                    openAppSettings();
                  } else {
                    //申请权限
                    isGoAppSetting = false;
                    requestPermission(context, permission);
                  }
                },
              ),
            ],
          );
        },
        context: _context);
  }

  void requestPermission(BuildContext context, Permission permission) async {
    //请求权限
    PermissionStatus status = await permission.request();

    //校验
    checkPermission(status: status);
  }

//关闭应用
  void closeAPP() {
    SystemChannels.platform.invokeMethod("SystemNavigator.pop");
  }
}
